import { getData } from '@/utils/request'

import { useLayoutEffect, useState } from 'react'

// 其他存储方式
export { getDictDataFromServer, useDictData }

interface DictDataEntity {
  dictType: number
  guid: string
  code: string
  name: string
}

interface DictDataEntityExpand {
  value?: string
  remark?: string
  picUrl?: string
  picUrl2?: string
  parentGUID?: string
  childDict?: any
}

type DictDataComb = DictDataEntity & DictDataEntityExpand

let init = false
let DictData: DictDataComb[] = []
let promise: Promise<any> | null

async function getDictDataFromServer(dictType?: number) {
  promise = getData<DictDataComb[], Partial<Pick<DictDataEntity, 'dictType'>>>(
    '/account/common/Bs/api/BasicData/GetDictData.htm',
    { dictType }
  )
  const { data, suc, message } = await promise
  init = true
  promise = null
  if (suc && data) {
    DictData = data
    return data
  }
  return Promise.reject(message)
}

/**
 * @desc 获取Dict字段hook
 */
function useDictData<U = DictDataComb>(
  filter:
    | number
    | ((
        value: Readonly<DictDataComb>,
        index: number,
        self: DictDataComb[]
      ) => boolean),
  mapper?: (
    value: Readonly<DictDataComb>,
    index: number,
    self: DictDataComb[]
  ) => U
) {
  const [data, setData] = useState<U[]>([])
  useLayoutEffect(() => {
    function fn() {
      if (typeof filter === 'number') {
        const dictType = filter
        filter = (v) => v.dictType === dictType
      }
      mapper = mapper ?? ((v: any) => ({ ...v }))
      setData(DictData.filter(filter).map(mapper))
    }

    if (init) {
      fn()
    } else {
      if (promise) {
        promise?.then(fn)
      } else {
        getDictDataFromServer().then(fn)
      }
    }
  }, [])
  return [data]
}
